<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form'
import type { VxeTableGridOptions } from '#/adapter/vxe-table'

import { h, ref, onMounted } from 'vue'
import { Page, useVbenModal } from '@vben/common-ui'
import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { getGoodsDeliveryTimeLogList, approvalGoodsDeliveryTimeLog, getTabsIndex } from '#/api/goodsDeliveryTimeLog'
import { getAdminList } from '#/api/common'
import { Button, message, Tooltip, Spin } from 'ant-design-vue'
import { AntPlusOutlined } from '@vben/icons'
import { useDebounceFn } from '@vueuse/core'
import countTabs from '#/adapter/component/count-tabs.vue'

import Form from './modules/form.vue'

interface RowType {
  [key: string]: any
}

interface TabItem {
  title: string
  value: string
  count: number
  type: 'success' | 'primary' | 'warning' | 'danger'
}

// 标签页数据
// 后端返回的 tabs 包含以下状态：
// - 全部
// - 待一审
// - 待二审
// - 已通过
// - 已拒绝
// - 已作废
const tabs = ref<TabItem[]>([
  { title: '全部', value: 'all', count: 0, type: 'primary' },
  { title: '待一审', value: '0', count: 0, type: 'warning' },
  { title: '待二审', value: '1', count: 0, type: 'warning' },
  { title: '已通过', value: '2', count: 0, type: 'success' },
  { title: '已拒绝', value: '3', count: 0, type: 'danger' },
  { title: '已作废', value: '99', count: 0, type: 'danger' },
])
const activeTab = ref('all')

// 获取选中的行数据
const selectedRows = ref<any>([])

// 关键词搜索
const keyword = ref({
  createAdmin_id: '',
})
const fetching = ref(false)

// 审核弹窗配置
const approvalConfig = ref({
  visible: false,
  row: null as any,
  confirmVisible: false,
  toStatus: 0,
  cancelText: '',
  confirmTitle: '',
})

const defaultSort: { field: string; order: '' | 'asc' | 'desc' | null } = {
  field: 'id',
  order: 'desc',
}

// 获取状态选项
const getStatusOptions = () => {
  return tabs.value.map(item => ({
    label: item.title,
    value: Number.parseInt(item.value),
    color: item.type
  }))
}

/**
 * 获取发起人选项
 */
async function fetchAdminOptions({ keyword = '' }: Record<string, any>) {
  const { list } = await getAdminList({
    quick_search: keyword,
    page: 1,
    limit: 100,
    initKey: 'id',
    initValue: undefined,
    select: true,
  })

  return list.map((item: any) => ({
    label: item.realname,
    value: item.id,
  }))
}

/**
 * 标签页切换
 * 点击不同的 tab 时，activeTab 值会自动更新，然后重新加载表格数据
 * navValue 参数会传递给后端 API 进行数据过滤
 */
const handleTabChange = () => {
  gridApi.reload()
}

const formOptions: VbenFormProps = {
  wrapperClass: 'grid-cols-5',
  schema: [
    {
      component: 'Input',
      fieldName: 'goodsPurchase*goods_purchase_sn',
      label: '采购单号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
        placeholder: '请输入采购单号',
      },
    },
    {
      component: 'Input',
      fieldName: 'goods*goods_no',
      label: '货号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
        placeholder: '请输入货号',
      },
    },
    {
      component: 'Input',
      fieldName: 'template*template_no',
      label: '简码',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
        placeholder: '请输入简码',
      },
    },
    {
      component: 'Input',
      fieldName: 'create_text',
      label: '申请原因',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
        placeholder: '请输入申请原因',
      },
    },
    {
      component: 'Select',
      fieldName: 'status',
      label: '审批状态',
      operator: '=',
      componentProps: {
        allowClear: true,
        options: [],
        placeholder: '请选择审批状态',
      },
    },
    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetchAdminOptions,
          filterOption: false,
          onSearch: useDebounceFn((value: string) => {
            keyword.value.createAdmin_id = value
          }, 300),
          params: {
            keyword: keyword.value.createAdmin_id || undefined,
          },
          showSearch: true,
          immediate: false,
          alwaysLoad: true,
          allowClear: true,
          visibleEvent: 'onFocus',
          onDropdownVisibleChange: (open: boolean) => {
            if (open) keyword.value.createAdmin_id = ''
          },
        }
      },
      fieldName: 'createAdmin*id',
      label: '发起人',
      operator: '=',
      renderComponentContent: () => {
        return {
          notFoundContent: fetching.value ? h(Spin) : undefined,
        }
      },
    },
    {
      component: 'RangePicker',
      fieldName: 'create_time',
      label: '发起时间',
      operator: 'RANGE',
      valueToString: true,
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
    },
  ],
  showCollapseButton: true,
  collapsed: true,
  submitOnChange: false,
  submitOnEnter: true,
}

const gridOptions: VxeTableGridOptions<RowType> = {
  border: true,
  checkboxConfig: {
    highlight: true,
    reserve: true,
    showReserveStatus: true,
  },
  rowConfig: {
    useKey: true,
    keyField: 'id',
    isHover: true,
  },
  columnConfig: {
    useKey: true,
  },
  columns: [
    { type: 'checkbox', width: 70, fixed: 'left' },
    { field: 'id', title: 'ID', fixed: 'left', sortable: true },
    { field: 'goodsPurchase.goods_purchase_sn', title: '采购单号', fixed: 'left' },
    { field: 'goods.goods_no', title: '货号' },
    { field: 'template.template_no', title: '简码' },
    {
      field: 'updateData',

      title: '申请修改内容',
      slots: { default: 'updateData' },
    },
    { field: 'create_text', width: 300, title: '申请原因' },
    {
      field: 'status',

      title: '审批状态',
      cellRender: { name: 'CellTag', options: getStatusOptions() },
    },
    {
      field: 'handle_text',

      title: '审批记录',
      slots: { default: 'handleText' },
    },
    { field: 'createAdmin.realname', width: 120, title: '发起人' },
    { field: 'create_time', width: 160, title: '发起时间', sortable: true },
    // {
    //   field: 'operation',
    //   fixed: 'right',
    //   slots: { default: 'operation' },
    //   title: '操作',
    // },
  ],
  exportConfig: {},
  height: 'auto',
  keepSource: true,
  pagerConfig: {
    pageSize: 20,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page, sort }) => {
        const search = await gridApi.formApi.getFiltersValues()
        const res = await getGoodsDeliveryTimeLogList({
          page: page.currentPage,
          limit: page.pageSize,
          search,
          order: sort.field && sort.order ? `${sort.field},${sort.order}` : `${defaultSort.field},${defaultSort.order}`,
          status: activeTab.value,
        })

        // 同时刷新 tab 统计数据
        const tabsRes = await getTabsIndex({ search })
        if (tabsRes) {
          tabs.value = tabsRes
        }

        return {
          items: res.list,
          total: res.total,
        }
      },
    },
    sort: true,
  },
  sortConfig: {
    defaultSort,
    remote: true,
  },
  toolbarConfig: {
    custom: true,
    export: true,
    refresh: true,
    resizable: true,
    search: true,
    zoom: true,
  },
  id: 'goods_delivery_time_log_list',
  customConfig: {
    storage: true,
  },
}

// 处理新建操作
const handleCreate = () => {
  FormModalApi.setData({ info: {} }).open()
}

/**
 * 处理审核操作
 * 审批状态说明：
 * - 0: 待一审
 * - 1: 待二审
 * - 2: 已通过
 * - 3: 已拒绝
 * - 99: 已作废
 */
const handleApproval = (row: any) => {
  approvalConfig.value.visible = true
  approvalConfig.value.row = row
}

// 确认审核
const handleConfirmApproval = (status: number) => {
  approvalConfig.value.confirmVisible = true
  approvalConfig.value.toStatus = status
  if (status === 1) {
    approvalConfig.value.confirmTitle = '一审通过'
  } else if (status === 2) {
    approvalConfig.value.confirmTitle = '二审通过'
  } else if (status === 3) {
    approvalConfig.value.confirmTitle = '拒绝'
  }
}

// 作废处理
const handleCancel = () => {
  approvalConfig.value.toStatus = 99
  handleApprovalSubmit()
}

// 提交审核
const handleApprovalSubmit = async () => {
  const hideLoading = message.loading({
    content: '处理中...',
    duration: 0,
    key: 'approval_process',
  })

  try {
    await approvalGoodsDeliveryTimeLog({
      id: approvalConfig.value.row.id,
      status: approvalConfig.value.toStatus,
      cancel_text: approvalConfig.value.cancelText,
    })
    message.success({
      content: '操作成功',
      key: 'approval_process',
    })
    approvalConfig.value.visible = false
    approvalConfig.value.confirmVisible = false
    approvalConfig.value.cancelText = ''
    gridApi.reload()
    fetchTabsData()
  } catch (error) {
    hideLoading()
  }
}

/**
 * 获取标签页数据
 * 标签页包含：全部、待一审、待二审、已通过、已拒绝、已作废
 */
const fetchTabsData = async () => {
  try {
    const res = await getTabsIndex()
    console.log('后端返回的 tabs 数据:', res)
    // 如果后端返回了数据，则使用后端数据更新 tabs
    if (res.data && res.data.length > 0) {
      tabs.value = res.data
      console.log('更新后的 tabs:', tabs.value)
    } else {
      console.log('使用默认 tabs 数据')
    }

    // 更新状态选项（用于搜索表单中的状态下拉框）
    const statusSchema = formOptions.schema?.find(item => item.fieldName === 'status')
    if (statusSchema && statusSchema.componentProps) {
      statusSchema.componentProps = {
        ...statusSchema.componentProps,
        options: tabs.value.map(item => ({
          label: item.title,
          value: item.value,
        }))
      }
    }
  } catch (error) {
    console.error('获取标签页数据失败:', error)
  }
}

const fetchData = async () => {
  gridApi.reload()
  fetchTabsData()
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents: {
    checkboxChange: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    },
    checkboxAll: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    },
    cellDblclick: ({ row }: { row: any }) => {
      handleApproval(row)
    },
  },
})

const [FormModal, FormModalApi] = useVbenModal({
  connectedComponent: Form,
})

onMounted(() => {
  console.log('初始 tabs 数据:', tabs.value)
  console.log('初始 activeTab:', activeTab.value)
  fetchTabsData()
})
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <div>
          <Button class="mr-2" type="primary" @click="handleCreate">
            <AntPlusOutlined />
            批量添加采购单号
          </Button>
          <div style=" width: 1000px;margin-top: 10px">
            <count-tabs v-model:active-key="activeTab" :list="tabs" @click-tab="handleTabChange" :disabled="false" />
          </div>
        </div>
      </template>

      <template #updateData="{ row }">
        <Tooltip placement="left">
          <template #title>
            <div v-if="row.updateData && row.updateData.length > 0">
              <div v-for="(item, index) in row.updateData" :key="index" class="mb-2">
                <div class="font-bold">{{ item.fieldName }}:</div>
                <div>改前: {{ item.origin }}</div>
                <div class="text-red-500">改后: {{ item.destination }}</div>
              </div>
            </div>
          </template>
          <span class="cursor-pointer text-blue-500">查看详情</span>
        </Tooltip>
      </template>

      <template #handleText="{ row }">
        <Tooltip placement="left">
          <template #title>
            <div v-if="row.text_arr && row.text_arr.length > 0">
              <div v-for="(item, index) in row.text_arr" :key="index" class="mb-2">
                <div>处理人: {{ item.username }}</div>
                <div>处理时间: {{ item.time }}</div>
                <div>处理结果: {{ item.text }}</div>
              </div>
            </div>
          </template>
          <Button size="small" type="link">查看详情</Button>
        </Tooltip>
      </template>

<!--      <template #operation="{ row }">-->
<!--        <Button-->
<!--          v-if="row.status === 0 || row.status === 1"-->
<!--          class="mr-2"-->
<!--          type="primary"-->
<!--          size="small"-->
<!--          @click.stop="handleApproval(row)"-->
<!--        >-->
<!--          审核-->
<!--        </Button>-->
<!--      </template>-->
    </Grid>

    <FormModal @fetch-data="fetchData" />
  </Page>
</template>
